package cn.dengta.webapp.risk.service;

import java.util.*;
import javax.annotation.Nonnull;

import cn.dengta.context.model.AppContext;
import cn.dengta.context.model.WesKit;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.risk.bean.RiskType;
import cn.dengta.webapp.risk.dao.RiskConfigDao;
import cn.dengta.webapp.risk.entity.RiskConfig;
import me.codeplayer.util.*;
import org.apache.dubbo.config.annotation.DubboService;

/**
 * 风控配置服务
 *
 * @author XiaoRong
 * @since 2022-06-05
 */
@DubboService
public class RiskConfigService extends BaseServiceImpl<RiskConfig, RiskConfigDao, Long> implements RemoteRiskConfigService {

	final LazyCacheLoader<Map<String, RiskConfig>> cacheLoader = new TimeBasedCacheLoader<>(EasyDate.MILLIS_OF_MINUTE, this::find);

	public Map<String, RiskConfig> find() {
		List<RiskConfig> list = baseDao.findAll();
		Map<String, RiskConfig> map = new HashMap<>(list.size(), 1F);
		if (X.isValid(list)) {
			for (RiskConfig config : list) {
				map.put(config.getScope() + "_" + config.getType(), config);
			}
		}
		return map;
	}

	@Nonnull
	public Map<String, RiskConfig> cache() {
		return cacheLoader.get();
	}

	public RiskConfig getOut(@Nonnull RiskType type) {
		String key = AppContext.OUT.ordinal() + "_" + type.value;
		return cache().get(key);
	}

	public RiskConfig get(WesKit wesKit, @Nonnull RiskType type) {
		final AppContext context = wesKit.isInterior() ? AppContext.INTER : AppContext.OUT;
		return get(context, type);
	}

	public RiskConfig get(AppContext context, @Nonnull RiskType type) {
		String key = context.ordinal() + "_" + type.value;
		return cache().get(key);
	}


	@Nonnull
	public Collection<RiskConfig> getConfigs() {
		Map<String, RiskConfig> map = cache();
		return map.values();
	}

	public boolean isOpen(RiskType riskType) {
		RiskConfig config = getOut(riskType);
		return config == null || config.isEnabled();
	}

	public boolean isOpen(WesKit wesKit, RiskType riskType) {
		RiskConfig config = get(wesKit, riskType);
		return config == null || config.isEnabled();
	}

	@Override
	public void flushCache() {
		cacheLoader.flush(true);
	}

}
